//创建用户相关的小仓库
import {defineStore} from 'pinia'
//引入操作本地存储的工具方法
import {
    GET_TOKEN,
} from '@/utils/storage'
//引入路由(常量路由)
import {anyRoute, constantRoute} from '@/router/routes'
import {filterAsyncRoute} from "@/utils";
import router from "@/router";
import {asyncRoute} from "@/router"
import _ from 'lodash'
import {getUserInfoApi} from "@/api/user";
import lodash from "lodash";
import {ElMessage} from '@/components'

interface UserStoreStateType {
    token: string | null,
    username: string,
    avatar: string,
    buttons: string[],
    menuRoutes: any[],
    routes: any[]
}

//创建用户小仓库
const useUserStore = defineStore('User', {
    state: (): UserStoreStateType => {
        return {
            token: GET_TOKEN(), //用户唯一标识token
            username: '',
            avatar: '',
            //存储当前用户是否包含某一个按钮权限
            buttons: [],
            menuRoutes: [],
            routes: []
        }
    },
    actions: {
        async getUserInfo() {
            const res = await getUserInfoApi()
            if (res.status === 0) {
                this.username = res.data.username;
                this.buttons = res.data.buttons;
                this.routes = res.data.routes;
                const userAsyncRoute = filterAsyncRoute(lodash.cloneDeep(asyncRoute), lodash.cloneDeep(res.data.routes))
                this.menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoute];
                console.log(userAsyncRoute);
                [...userAsyncRoute, anyRoute].forEach(route => {
                    router.addRoute(route)
                })
                if (res.data.routes.length === 0 && res.data.routes.length === 0) {
                    ElMessage({
                        type: 'warning',
                        message: res.msg,
                    })
                    await router.push('/home')
                    return Promise.resolve({message: res.msg})
                }
                return Promise.resolve('成功')
            } else {
                return Promise.reject('失败')
            }
        },
        userLogout() {
            //退出登录以后清除动态路由，防止下一个登录得人可以看到上个用户看到的权限
            this.menuRoutes = [...constantRoute];
            this.token = '';
            this.username = ''
            localStorage.removeItem('Token')

        },
        removeAsyncRoute(menuRoutes) {
            menuRoutes.forEach(route => {
                console.log(route);
                if (route.children) {
                    this.removeAsyncRoute(route.children)
                } else {
                    router.removeRoute(route.name)
                }

            })
        }
    },
    getters: {}
})

//对外暴露获取小仓库方法
export default useUserStore
